package com.asktgapp.user.fragment;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.ChooseStateFragment;
import com.asktgapp.dialog.ChooseTypeFragment;
import com.asktgapp.dialog.ConfirmPublishDialog;
import com.asktgapp.dialog.DatePickerFragment;
import com.asktgapp.dialog.JgLowDialog;
import com.asktgapp.dialog.PublishSuccessDialog;
import com.asktgapp.model.AddIMGVO;
import com.asktgapp.model.BrandVO;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.model.ImgUrlVO;
import com.asktgapp.model.LawVO;
import com.asktgapp.model.NetIMGVO;
import com.asktgapp.model.RentDetialVO;
import com.asktgapp.modulebase.ServiceUtil;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.ChooseBrandActivity;
import com.asktgapp.user.activity.ChooseCityActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.utils.SelectPhotoDialogFragment;
import com.bigkoo.pickerview.TimePickerView;
import com.jph.takephoto.model.TImage;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/31
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class EditRentFragment extends BaseFragment {
    @InjectView(R.id.tv_publish)
    TextView mPublish;
    @InjectView(R.id.recycle_photo)
    RecyclerView mPhotoRecyclerView;
    @InjectView(R.id.tv_machine_type)
    TextView mChooseTypeTv;
    @InjectView(R.id.tv_brand)
    TextView mChooseBrandTv;
    @InjectView(R.id.tv_address)
    TextView mChooseAddress;
    @InjectView(R.id.tv_made_date)
    TextView mMadeDate;
    @InjectView(R.id.tv_state)
    TextView mStateTV;
    @InjectView(R.id.et_remark)
    EditText mRemarkET;
    @InjectView(R.id.et_name)
    EditText mLinkNameET;
    @InjectView(R.id.et_phone)
    EditText mLinkPhoneET;
    @InjectView(R.id.cb_law)
    CheckBox lawCb;
    @InjectView(R.id.et_price)
    EditText mPriceET;
    @InjectView(R.id.et_version)
    EditText mVersionET;
    @InjectView(R.id.et_weight)
    EditText mWeightET;
    @InjectView(R.id.tv_law_fb)
    TextView mLawtv;
    private LawVO mLawVO;
    private BaseAdapter mBaseAdapter;
    private List<ImgUrlVO> imgUrl;
    private List<DeviceTypeVO> mTypeList = new ArrayList<>();
    private List<BrandVO> mBrandList = new ArrayList<>();
    private String mSelectedTypeId;
    private String mSelectedBrandId;
    private String mselectedAddressCity;
    private String mSelectedAddressArea;
    private String mCityId;
    private String mAreaId;
    private String mDate;
    private String mWorkHours;
    private int mDeviceID;
    private RentDetialVO.DataInfoBean rentDetialVO;
    private List<NetIMGVO> oldUrls = new ArrayList<>();
    private List allURls = new ArrayList();//所有要展示的url
    private int IMGWidth;
    private EmojiFilter inputFilter;
    InputFilter[] inputFilters;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_rent_publish, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    private void setUI(RentDetialVO.DataInfoBean bean) {

        mPriceET.setText(String.valueOf(Utils.D2I(bean.getPrice())));
        mChooseTypeTv.setText(bean.getTypeName());
        mSelectedTypeId = String.valueOf(bean.getType_id());
        mChooseBrandTv.setText(bean.getBrand());
        mSelectedBrandId = String.valueOf(bean.getBrand_id());
        mChooseAddress.setText(bean.getPro_name().replace("省", "") + bean.getCity_name());
        mAreaId = String.valueOf(bean.getArea_id());
        mCityId = String.valueOf(bean.getCity_id());
        mMadeDate.setText(Utils.getDateYMD(bean.getProduction_date()));
        mRemarkET.setText(bean.getInfo());
        mLinkNameET.setText(bean.getLink_name());
        mLinkPhoneET.setText(bean.getLink_phone());
        lawCb.setChecked(true);
        mVersionET.setText(bean.getModel());
        mWeightET.setText(String.valueOf(Utils.DtS(bean.getTonnage())));
        //待售
        if (bean.getState() == 0) {
            mStateTV.setText("待租");
        } else {
            mStateTV.setText("忙碌");
        }
        String[] url;
        oldUrls.clear();
        imgUrl.clear();
        if (!Util.isEmpty(bean.getBanner_pic())) {
            url = bean.getBanner_pic().split(",");
            for (int i = 0; i < url.length; i++) {
                oldUrls.add(new NetIMGVO(url[i]));
            }
        }
        setAdpterData();

    }

    public void setAdpterData() {
        allURls.clear();
        if (oldUrls.size() > 0) {
            allURls.addAll(oldUrls);
        }
        if (imgUrl.size() > 0) {
            allURls.addAll(imgUrl);
        }
        mBaseAdapter.setData(allURls);
        if (allURls.size() < 12) {
            mBaseAdapter.addData(BaseAdapter.AddType.LASE, new AddIMGVO());
        }
    }

    @Override
    protected void initView(View rootView) {
        inputFilter=new EmojiFilter();
        inputFilters=new InputFilter[]{inputFilter};
        mRemarkET.setFilters(inputFilters);
        mLinkNameET.setFilters(inputFilters);
        mLinkPhoneET.setFilters(inputFilters);
        mPriceET.setFilters(inputFilters);
        mVersionET.setFilters(inputFilters);
        mWeightET.setFilters(inputFilters);
        WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        IMGWidth = display.getWidth() / 5;
        imgUrl = new ArrayList();
        mDeviceID = getActivity().getIntent().getIntExtra("deviceid", 0);
        getBaseActivity().setBackNavigationIcon();
        mPublish.setOnClickListener(this);
        mChooseTypeTv.setOnClickListener(this);
        mChooseBrandTv.setOnClickListener(this);
        mChooseAddress.setOnClickListener(this);
        mMadeDate.setOnClickListener(this);
        mStateTV.setOnClickListener(this);
        mLawtv.setOnClickListener(this);
        mPhotoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = null;
                if (viewType == 0) {
                    //网络图片
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_select_photo, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, final Object data) {
                            ImageView imageView = holder.getView(R.id.img);
                            final ImageView delete = holder.getView(R.id.iv_delete);
                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
                            params.width = IMGWidth;
                            params.height = IMGWidth;
                            imageView.setLayoutParams(params);
                            if (data instanceof NetIMGVO) {
                                final NetIMGVO bean = (NetIMGVO) data;
                                delete.setVisibility(View.VISIBLE);
                                ImageDisplayUtil.LoadNetImageWithUrl(imageView, getActivity(), bean.getUrl());
                                delete.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        oldUrls.remove(bean);
                                        setAdpterData();
                                    }
                                });
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
//// TODO: 2018/3/8  看大图

                        }
                    });
                } else if (viewType == 1) {
                    //本地图片
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_select_photo, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            ImageView imageView = holder.getView(R.id.img);
                            final ImageView delete = holder.getView(R.id.iv_delete);
                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
                            params.width = IMGWidth;
                            params.height = IMGWidth;
                            imageView.setLayoutParams(params);
                            if (data instanceof ImgUrlVO) {
                                final ImgUrlVO bean = (ImgUrlVO) data;
                                ImageDisplayUtil.LoadDisImage(getActivity(), imageView, bean.getUrl());
                                delete.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        imgUrl.remove(bean);
                                        setAdpterData();
                                    }
                                });
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {

                        }
                    });
                } else if (viewType == 2) {
                    //添加
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_picture_add, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            ImageView imageView = holder.getView(R.id.img);
                            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) imageView.getLayoutParams();
                            params.width = IMGWidth;
                            params.height = IMGWidth;
                            imageView.setLayoutParams(params);
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            onPickPhoto();

                        }
                    });
                }
                return holder;

            }

            @Override
            public int getItemViewType(int position) {
                Object bean = mBaseAdapter.getData().get(position);
                if (bean instanceof NetIMGVO) {
                    return 0;
                } else if (bean instanceof ImgUrlVO) {
                    return 1;
                } else if (bean instanceof AddIMGVO) {
                    return 2;
                } else return 1;

            }
        };
        mPhotoRecyclerView.setAdapter(mBaseAdapter);
    }


    private void onPickPhoto() {
        SelectPhotoDialogFragment selectPhotoDialogFragment = new SelectPhotoDialogFragment(new SelectPhotoDialogFragment.setResult() {
            @Override
            public void setResult(ArrayList<TImage> mImages) {
                for (TImage img : mImages) {
                    ImgUrlVO bean = new ImgUrlVO(img.getPath());
                    imgUrl.add(bean);
                }
                setAdpterData();
            }
        }, 12 - (imgUrl.size() + oldUrls.size()));
        selectPhotoDialogFragment.show(getFragmentManager(), "selectPhotoDialogFragment");
    }


    @Override
    public void loadData() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    mTypeList = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 0);
            }
        });
        visibleLoading();
        HashMap param = new HashMap();
        param.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        param.put("id", mDeviceID);
        param.put("type", 0);
        Call<ApiResponseBody<RentDetialVO>> call1 = apiservice.getRentDetail(param);
        call1.enqueue(new Callback<ApiResponseBody<RentDetialVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<RentDetialVO>> call, Response<ApiResponseBody<RentDetialVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    rentDetialVO = response.body().getResult().getDataInfo();
                    setUI(rentDetialVO);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<RentDetialVO>> call, Throwable t) {
                inVisibleLoading();
                visibleNoData();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

        params.put("type", 8);
        Call<ApiResponseBody<LawVO>> call2 = apiservice.xieyiInfo(params);
        call2.enqueue(new Callback<ApiResponseBody<LawVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LawVO>> call, Response<ApiResponseBody<LawVO>> response) {
                if (response.isSuccessful()) {
                    mLawVO = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LawVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_publish:
                hideSoftKeyboard();
                if (imgUrl.size() == 0 && oldUrls.size() == 0) {
                    showTost("请选择机械图片", 1);
                    return;
                }
                if (Util.isEmpty(mPriceET.getText().toString().trim())) {
                    showTost("请输入价格", 1);
                    return;
                }
                if (Util.isEmpty(mSelectedTypeId) || Util.isEmpty(mChooseTypeTv.getText().toString().trim())) {
                    showTost("请选择设备类型", 1);
                    return;
                }
                if (Util.isEmpty(mSelectedBrandId) || Util.isEmpty(mChooseBrandTv.getText().toString().trim())) {
                    showTost("请选择品牌", 1);
                    return;
                }
                if (Util.isEmpty(mVersionET.getText().toString())) {
                    showTost("请输入型号", 1);
                    return;
                }
                if (mVersionET.getText().toString().length() > 20) {
                    showTost("型号长度不能超过20字,当前字数" + mVersionET.getText().toString().length(), 1);
                    return;
                }
                if (Util.isEmpty(mWeightET.getText().toString())) {
                    showTost("请输入吨位", 1);
                    return;
                }
                if (Util.isEmpty(mMadeDate.getText().toString())) {
                    showTost("请选择出厂日期", 1);
                    return;
                }
                if (Util.isEmpty(mChooseAddress.getText().toString()) || Util.isEmpty(mAreaId)) {
                    showTost("请选择设备所在地", 1);
                    return;
                }
                if (Util.isEmpty(mStateTV.getText().toString())) {
                    showTost("请选择设备状态", 1);
                    return;
                }
                if (Util.isEmpty(mRemarkET.getText().toString()) || mRemarkET.getText().toString().length() < 10) {
                    showTost("请输入补充说明（最少十个字）", 1);
                    return;
                }
                if (mRemarkET.getText().toString().length() > 200) {
                    showTost("补充说明字数不能超过200字，当前字数：" + mRemarkET.getText().toString().length(), 1);
                    return;
                }
                if (Util.isEmpty(mLinkNameET.getText().toString())) {
                    showTost("请输入联系人姓名", 1);
                    return;
                }
                if (Util.isEmpty(mLinkPhoneET.getText().toString())) {
                    showTost("请输入联系电话", 1);
                    return;
                }
                if (!lawCb.isChecked()) {
                    showTost("您未勾选发布协议，如果您同意该协议，请勾选", 1);
                    return;
                }

                ConfirmPublishDialog confirmPublishDialog = new ConfirmPublishDialog(new ConfirmPublishDialog.onResultCallBack() {
                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onSure() {
                        requestNetAndPublish();

                    }
                }, "确认发布编辑后的出租信息？");
                confirmPublishDialog.show(getFragmentManager(), "ConfirmPublishDialog");
                break;

            case R.id.tv_machine_type:
                ChooseTypeFragment chooseTypeFragment = new ChooseTypeFragment(new ChooseTypeFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mChooseTypeTv.setText(s[1]);
                        mSelectedTypeId = s[0];
                        getBrandLlist();
                        mChooseBrandTv.setText("");
                    }
                }, mTypeList, "请选择设备类型");
                chooseTypeFragment.show(getFragmentManager(), "ChooseTypeFragment");
                break;


            case R.id.tv_brand:
                if (Util.isEmpty(mChooseTypeTv.getText().toString().trim())) {
                    showTost("请先选择设备类型", 1);
                    return;
                }
//
//                ChooseBrandDialogFragment chooseBrandFragment = new ChooseBrandDialogFragment(new ChooseBrandDialogFragment.Callback() {
//                    @Override
//                    public void onSelect(String... s) {
//                        mSelectedBrandId = s[0];
//                        mChooseBrandTv.setText(s[1]);
//                    }
//                }, mBrandList, "请选择品牌");
//                chooseBrandFragment.show(getFragmentManager(), "ChooseTypeFragment");
                Intent intent = new Intent(getActivity(), ChooseBrandActivity.class);
                intent.putExtra("typeId", mSelectedTypeId);
                startActivityForResult(intent, 200);
                break;

            case R.id.tv_address:
                Intent address = new Intent(getActivity(), ChooseCityActivity.class);
                startActivityForResult(address, 300);

                break;
            case R.id.tv_made_date:
//                DatePickerFragment picker = new DatePickerFragment(new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//
//                        mDate = Utils.getDateString(year, month, dayOfMonth);
//                        if (!Utils.isGoneDate(mDate)) {
//                            showTost("不能选择将来的时间！", 1);
//                        } else
//                            mMadeDate.setText(mDate);
//                    }
//                });
//                picker.show(getFragmentManager(), "DatePickerFragment");
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        if (!Utils.isGoneDate(Util.DateToStr(date2, "yyyy-MM-dd"))) {
                            showTost("不能选择将来的时间！", 1);
                        } else
                            mMadeDate.setText(Util.DateToStr(date2, "yyyy-MM-dd"));

                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(20)//滚轮文字大小
                        .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(JGColor.APP_BASIC_BLUE)//确定按钮文字颜色
                        .setCancelColor(JGColor.APP_BASIC_BLUE)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;

            case R.id.tv_state:
                List<String> list = new ArrayList<>();
                list.add("待租");
                list.add("忙碌");
                ChooseStateFragment chooseStateFragment = new ChooseStateFragment(new ChooseStateFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mStateTV.setText(s[0]);
                    }
                }, list, "");
                chooseStateFragment.show(getFragmentManager(), "ChooseStateFragment");
                break;
            case R.id.tv_law_fb:
                JgLowDialog jgLowDialog1 = new JgLowDialog("发布协议", mLawVO.getContent());
                jgLowDialog1.show(getFragmentManager(), "JgLowDialog1");
                break;

        }

    }

    private void getBrandLlist() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("typeId", mSelectedTypeId);
        Call<ApiResponseBody<List<BrandVO>>> call = apiservice.getBrandList(params);
        call.enqueue(new Callback<ApiResponseBody<List<BrandVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<BrandVO>>> call, Response<ApiResponseBody<List<BrandVO>>> response) {
                if (response.isSuccessful()) {
                    mBrandList = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<BrandVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);

            }
        });

    }

    private void requestNetAndPublish() {

        HashMap params = new HashMap();
        final Apiservice apiservice = ApiUtil.getInstance().create();
        ApiUtil.putDefultData(getActivity(), params);
        params.put("id", RequestBody.create(ServiceUtil.MULTIPART, String.valueOf(mDeviceID)));
        params.put("isDel", RequestBody.create(ServiceUtil.MULTIPART, String.valueOf(0)));
        params.put("price", RequestBody.create(ServiceUtil.MULTIPART, mPriceET.getText().toString().trim()));
        params.put("typeId", RequestBody.create(ServiceUtil.MULTIPART, mSelectedTypeId));
        params.put("brandId", RequestBody.create(ServiceUtil.MULTIPART, mSelectedBrandId));
        params.put("model", RequestBody.create(ServiceUtil.MULTIPART, mVersionET.getText().toString().trim()));
        params.put("tonnage", RequestBody.create(ServiceUtil.MULTIPART, mWeightET.getText().toString().trim()));
        params.put("cityId", RequestBody.create(ServiceUtil.MULTIPART, mCityId));
        params.put("areaId", RequestBody.create(ServiceUtil.MULTIPART, mAreaId));
        params.put("productionDate", RequestBody.create(ServiceUtil.MULTIPART, mMadeDate.getText().toString().trim()));
//        params.put("workingHours", RequestBody.create(ServiceUtil.MULTIPART, mWorkHourET.getText().toString().trim()));
        params.put("info", RequestBody.create(ServiceUtil.MULTIPART, mRemarkET.getText().toString().trim()));
        params.put("linkName", RequestBody.create(ServiceUtil.MULTIPART, mLinkNameET.getText().toString().trim()));
        params.put("linkPhone", RequestBody.create(ServiceUtil.MULTIPART, mLinkPhoneET.getText().toString().trim()));
        if (mStateTV.getText().toString().trim().equals("待租")) {
            params.put("state", RequestBody.create(ServiceUtil.MULTIPART, "0"));
        } else if (mStateTV.getText().toString().trim().equals("忙碌")) {
            params.put("state", RequestBody.create(ServiceUtil.MULTIPART, "1"));
        }
        if (oldUrls.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < oldUrls.size(); i++) {
                stringBuilder.append(oldUrls.get(i).getUrl());
                if (i != (oldUrls.size() - 1)) {
                    stringBuilder.append(",");
                }
            }
            params.put("old_pic", RequestBody.create(ServiceUtil.MULTIPART, stringBuilder.toString()));
        }
        List<String> url = new ArrayList<>();
        for (ImgUrlVO vo : imgUrl) {
            url.add(vo.getUrl());
        }
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.subLease(params, ApiUtil.files2Parts("bannerPic", url.toArray(), ApiUtil.MULTIPART));
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
//                    PublishSuccessDialog publishSuccessDialog = new PublishSuccessDialog();
//                    publishSuccessDialog.setOnDismiss(new PublishSuccessDialog.onDissmissListener() {
//                        @Override
//                        public void onDismiss() {
                    showTost("发布成功", 1);
                    getActivity().finish();
//                        }
//                    });
//                    publishSuccessDialog.show(getFragmentManager(), "PublishSuccessDialog");
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
        //when success


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200) {
                mChooseBrandTv.setText(data.getStringExtra("brand"));
                mSelectedBrandId = data.getStringExtra("brandId");
            }
            if (requestCode == 300) {
                mAreaId = data.getStringExtra("areaId");
                mCityId = data.getStringExtra("cityId");
                mChooseAddress.setText(data.getStringExtra("area") + "  " + data.getStringExtra("city"));
            }
        }
    }
}
